"""
Case Type   : CLEAN CONNECTION
Case Name   : CLEAN CONNECTION TO ALL 指定不存在的用户和数据库，合理报错
Create At   : 2022-05-10
Owner       : liu-tong-8848
Description :
    1、删除数据库
    2、删除用户
    3、起线程执行清理操作
    4、清理环境
Expect      :
    1、删除数据库，expect: 成功
    2、删除用户，expect: 成功
    3、执行清理操作，expect: 成功
    4、清理环境，expect: 成功
History     :
"""

import os
import unittest
from yat.test import Node

from testcase.utils.Common import Common
from testcase.utils.CommonSH import CommonSH
from testcase.utils.Constant import Constant
from testcase.utils.Logger import Logger


class CleanConnection(unittest.TestCase):

    def setUp(self):
        self.log = Logger()
        self.log.info(f'-----{os.path.basename(__file__)} start-----')
        self.com = Common()
        self.pri_sh = CommonSH('PrimaryDbUser')
        self.pri_root = Node('PrimaryRoot')
        self.constant = Constant()
        self.u_name = 'u_clean_0023'
        self.db_name = 'd_clean_0023'
        self.flag = f'ERROR:  database "{self.db_name}" does not exist'

    def test_main(self):
        step_txt = '----step1: 删除数据库，expect: 成功----'
        self.log.info(step_txt)
        drop_sql = f'drop database if exists {self.db_name};'
        drop_result = self.pri_sh.execut_db_sql(drop_sql)
        self.log.info(drop_result)
        self.assertTrue(
            drop_result.count(self.constant.DROP_DATABASE_SUCCESS) == 1,
            '执行失败:' + step_txt)

        step_txt = '----step2: 删除用户，expect: 成功----'
        self.log.info(step_txt)
        drop_sql = f'drop user if exists {self.u_name} cascade;'
        drop_result = self.pri_sh.execut_db_sql(drop_sql)
        self.log.info(drop_result)
        self.assertTrue(
            drop_result.count(self.constant.DROP_ROLE_SUCCESS_MSG) == 1,
            '执行失败:' + step_txt)

        step_txt = '----step3: 执行清理操作，expect: 成功----'
        self.log.info(step_txt)
        sql_cmd1 = f'clean connection to all for database {self.db_name} ' \
                   f'to user {self.u_name};'
        clean_result = self.pri_sh.execut_db_sql(sql_cmd1)
        self.log.info(clean_result)
        self.assertIn(self.flag, clean_result, '执行失败:' + step_txt)

    def tearDown(self):
        self.log.info('----this is teardown----')
        step_txt = '----step4: 删除数据库和用户----'
        self.log.info(step_txt)
        drop_sql = f'drop database if exists {self.db_name};' \
                   f'drop user if exists {self.u_name} cascade;'
        drop_result = self.pri_sh.execut_db_sql(drop_sql)
        self.log.info(drop_result)

        self.log.info(f'-----{os.path.basename(__file__)} end-----')
